import md5 from 'js-md5';
import $ from 'jquery';

let APPID = '09c88f74955be099';
let SECRET_KEY = 'SKI6AZ1iCwx9UXPqWUezGc4np9MeZUWK';

/**
 * 有道翻译
 * @param {Object} str
 */
let Translate = function(str, from, to, callback) {
	var salt = (new Date).getTime();

	var str1 = APPID + str + salt + SECRET_KEY;
	var sign = md5(str1);
	if('auto' === from) {
		from = '';
	}

	$.ajax({
		url: 'http://openapi.youdao.com/api',
		type: 'post',
		dataType: 'jsonp',
		data: {
			q: str,
			appKey: APPID,
			salt: salt,
			from: from,
			to: to,
			sign: sign
		},
		success: function(data) {
			var trans_result = data.translation;
			var result = '';
			for(var i = 0; i < trans_result.length; i++) {
				var tran = trans_result[i];
				result += tran;
			}
			callback(result);
		}
	});
};

export default Translate;